package com.xhy.tool.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhy.tool.entity.User;
import com.xhy.tool.service.UserService;
import com.xhy.tool.utils.JwtUtils;
import com.xhy.tool.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author: Xhy
 * CreateTime: 2022-06-04 12:04
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R login(String name,String password){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userService.getOne(wrapper.eq("name", name));
        if (ObjectUtils.isEmpty(user)) return R.error().message("没有该账号");

        if (!user.getPassword().equals(password)) return R.error().message("密码不一致");

        // 登录成功，生成token
        String token = JwtUtils.getJwtToken(String.valueOf(user.getId()), user.getName());

        return R.ok().data("token",token).data("name",name);
    }
}
